import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutterprintapp/blue_device_model_entity.dart';
import 'package:flutterprintapp/methodChannelManager.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<String> msg = List();
  var _devicesList = List();
  var errorMsg = "open result";
  var version = "debug version:1.1.1";
  bool touchScan = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    MethodChannelManager.instance.setMethodCallHandler(onScan: (arguments) {
      setState(() {
        msg.add(arguments);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: CustomScrollView(
        slivers: <Widget>[
          title(version),
          title("蓝牙设备信息"),
          title(errorMsg),
          SliverToBoxAdapter(
            child: Visibility(
              visible: touchScan,
              child: _devicesList == null
                  ? Text("读取蓝牙设备失败，请检查蓝牙连接")
                  : (_devicesList.length == 0
                      ? Text("没有可用的蓝牙设备")
                      : ListView.builder(
                          shrinkWrap: true,
                          physics: NeverScrollableScrollPhysics(),
                          itemCount: _devicesList.length,
                          itemBuilder: (BuildContext context, int index) {
                            return _deviceInfo(index);
                          })),
            ),
          ),
          title("扫描信息"),
          SliverToBoxAdapter(
            child: ListView.builder(
                shrinkWrap: true,
                physics: NeverScrollableScrollPhysics(),
                itemCount: msg.length,
                itemBuilder: (BuildContext context, int index) {
                  return _deviceScanString(index);
                }),
          ),
        ],
      ),
      bottomNavigationBar: Row(
        children: <Widget>[
          FlatButton(
              onPressed: () async {
                final list =
                    await MethodChannelManager.instance.getBlueDevices();
                setState(() {
                  touchScan = true;
                  _devicesList = list;
                });
              },
              color: Colors.blue,
              child: Text('获取蓝牙设备')),
          Padding(padding: EdgeInsets.all(5.0)),
          FlatButton(
              onPressed: () {
                setState(() {
                  _devicesList = List();
                  msg = List();
                });
              },
              color: Colors.blue,
              child: Text('清空')),
        ],
      ),
    );
  }

  Widget title(String title) {
    return SliverToBoxAdapter(
      child: Text(
        title,
        style: TextStyle(fontSize: 16.0, color: Colors.red),
      ),
    );
  }

  Widget _deviceInfo(int index) {
    final entity = new Map<String, String>.from(_devicesList[index]);
    BlueDeviceModelEntity blue = BlueDeviceModelEntity().fromJson(entity);
//     或者如下解析
//    String deviceName=entity["deviceName"];
//    String deviceAddress=entity["deviceAddress"];
    return Container(
      width: MediaQuery.of(context).size.width,
      padding: EdgeInsets.all(5.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          FlatButton(
            color: Colors.blue,
            onPressed: () async {
              final response = await MethodChannelManager.instance
                  .openPrint(blue.deviceAddress);
              setState(() {
                errorMsg = "open result：" +
                    response["result"].toString() +
                    " " +
                    response["msg"];
              });
              if (!response["result"]) {
                return;
              }
              MethodChannelManager.instance.sendBytes([0x1B, 0x40]);
              MethodChannelManager.instance.sendBytes([0x1B, 0x61, 0x01]);
              MethodChannelManager.instance.sendString("*****华丽的分割线*****\n");
              MethodChannelManager.instance.sendBytes([0x1B, 0x61, 0x00]);
              MethodChannelManager.instance.sendString("测试开始\n");
              MethodChannelManager.instance
                  .sendString("(1、标题，居中，3倍大小，下划线，粗体)\n");
              MethodChannelManager.instance.sendBytes([0x1B, 0x61, 0x01]);
              MethodChannelManager.instance.sendBytes([0x1D, 0x21, 0x22]);
              MethodChannelManager.instance.sendBytes([0x1B, 0x45, 0x01]);
              MethodChannelManager.instance.sendBytes([0x1B, 0x2D, 0x32]);
              MethodChannelManager.instance.sendBytes([0x1B, 0x40]);
              MethodChannelManager.instance.sendString("\n");
              MethodChannelManager.instance
                  .sendString("(打印条码：1234567891234)\n");
              MethodChannelManager.instance.sendBarString("1234567891234");
              MethodChannelManager.instance.sendString("\n");
              MethodChannelManager.instance
                  .sendString("(打印条码：19ATZ-. \$/+%D)\n");
              MethodChannelManager.instance.sendBarString("19ATZ-. \$/+%D");
              MethodChannelManager.instance.sendString("\n");
              MethodChannelManager.instance.sendString("(二维条码DataMatrix)\n");
              MethodChannelManager.instance
                  .sendQRString("123-DataMatrix-二维码测试-321\0");
              MethodChannelManager.instance.closePrint();
            },
            child:
                Text(blue.deviceName + "————" + blue.deviceAddress + "，点击测试打印"),
          ),
          FlatButton(
              color: Colors.green,
              onPressed: () async {
                final response = await MethodChannelManager.instance
                    .openPrint(blue.deviceAddress);
                setState(() {
                  errorMsg = "open result：" +
                      response["result"].toString() +
                      " " +
                      response["msg"];
                });
                if (!response["result"]) {
                  return;
                }
                MethodChannelManager.instance.test(blue.deviceAddress);
              },
              child: Text("测试完全原生打印")),
        ],
      ),
    );
  }

  Widget _deviceScanString(int index) {
    return Container(
      width: MediaQuery.of(context).size.width,
      padding: EdgeInsets.all(10.0),
      child: Text(msg[index]),
    );
  }
}
